package com.example.mxs.service;

import com.example.mxs.dao.UserRepository;
import com.example.mxs.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;
    @Override
    public User findUserById(int id) {
        //return userDao.getOne(Integer.parseInt(id));
        Optional<User> optional = userRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        } else return null;
    }

    @Override
    public User findUserByName(String name) {
        return userRepository.findByUsername(name);
    }

    //保存用户
    @Override
    public User addUser(User user) {
        return userRepository.save(user);
    }

    /*
    * 分页返回数据
    * page 返回第几页，从0开始
    * */
    @Override
    public Page<User> findAllUser(Integer page, Integer size) {
        Pageable pageable =  PageRequest.of(page, size,Sort.Direction.ASC,"id");
        return userRepository.findAll(pageable);
    }

    /*
    *根据姓名查找用户列表
    * */
    @Override
    public Page<User> findAllUserByName(Integer page, Integer size,User user) {
        Pageable pageable =  PageRequest.of(page, size,Sort.Direction.ASC,"id");
        Example<User> example=Example.of(user);
        return userRepository.findAll(example,pageable);
    }


    /*
    * 更新用户信息
    * */
    public User update(int id,User user){
        user.setId(id);
        return userRepository.save(user);
    }

    /*删除用户*/
    public void delete(int id){
        userRepository.deleteById(id);
    }
}
